package v1

import (
	"ginblog/middleware"
	"ginblog/model"
	"ginblog/utils"
	"ginblog/utils/cos"
	"ginblog/utils/errmsg"
	"net/http"

	"github.com/gin-gonic/gin"
)

// Login 登陆验证函数
func Login(c *gin.Context) {
	var data model.User
	var token string
	var code int
	if err := c.ShouldBindJSON(&data); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"status":  errmsg.ERROR,
			"message": err.Error(),
			"token":   nil,
		})
		return
	}

	code = model.CheckLogin(data.Username, data.Password)
	if code == errmsg.SUCCESS {
		token, code = middleware.SetToken(data.Username)
	}
	c.JSON(http.StatusOK, gin.H{
		"status":  code,
		"message": errmsg.GetErrMsg(code),
		"token":   token,
	})
}

// GetTempCredential 获取上传文件临时cos密钥
func GetTempCredential(c *gin.Context) {
	userImgPath := c.Query("userImgPath")

	opt := cos.Options{
		AppID:        utils.AppID,
		Bucket:       utils.Bucket,
		Region:       utils.Region,
		COSSecretID:  utils.COSSecretID,
		COSSecretKEY: utils.COSSecretKEY,
		UserImgPath:  userImgPath,
	}
	credentials, code := cos.GetTempCredential(&opt)
	c.JSON(http.StatusOK, gin.H{
		"status":  code,
		"message": errmsg.GetErrMsg(code),
		"data":    credentials,
	})
}
